<template>
  <div class="app">
    <div>
      <el-upload
        class="upload-demo"
        action=""
        :auto-upload="false"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :on-change="fileChange"
        accept=".txt"
        multiple
        :limit="3"
        :on-exceed="handleExceed"
        :file-list="fileList"
        :on-progress="progress"
      >
        <el-button size="small" type="primary">点击上传编辑</el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传txt文件，且不超过500kb
        </div>
      </el-upload>
    </div>
    <!-- 编辑窗口 -->
    <div class="box-card-title">
      <el-card class="box-card">
        <el-input
          type="textarea"
          placeholder="请输入内容"
          v-model="text"
          style="width:100%;height:100%;"
          :rows="30"
          @input="changTextarea"
        >
        </el-input>
        <div class="tip">编辑完成后请重新另存为该文件</div>
        <div>
          <el-badge :value="changFlag" class="item">
            <el-button type="success" @click="saveAs">另存为</el-button>
          </el-badge>
          <el-autocomplete
            class="inputKeyword"
            popper-class="my-autocomplete"
            v-model="state"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @select="handleSelect"
          >
            <i
              class="el-icon-edit el-input__icon"
              slot="suffix"
              @click="handleIconClick"
            >
            </i>
            <template slot-scope="{ item }">
              <div class="name">{{ item.value }}</div>
            </template>
          </el-autocomplete>
          <el-button type="primary" class="el-icon-search" @click="retrieval"
            >检索</el-button
          >
          <el-button type="primary" class="goBack" @click="goBack"
            >返回</el-button
          >
        </div>
      </el-card>
    </div>
    <!-- 有违规关键字   -->
    <el-dialog title="违规文章" :visible.sync="dialogFormVisible">
      <div id="content" v-html="exhibition">{{ exhibition }}</div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogFormVisible = false"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { keyword } from '@/mock/keyword.js'
import { timeStampFormatStr } from '@/util/dataTimeUtil.js'
export default {
  data() {
    return {
      fileList: [],
      file: null,
      text: '', // input框中的值
      exhibition: '', // 违规内容展示
      testRes: '', // 读取文件中的值
      changFlag: '', // 更改标记
      restaurants: [], // 违规关键字数组
      state: '', // 违规字符
      dialogFormVisible: false // 违规弹窗展示
    }
  },
  methods: {
    // 删除文件钩子
    handleRemove(file, fileList) {
      this.testRes = ''
      console.log(file, fileList)
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      this.readT(file)
    },
    // 文件发送改变钩子
    fileChange(file) {
      this.readT(file)
    },
    // 文件上传前的钩子
    progress(file) {
      console.info(file)
    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 另存为按钮
    saveAs() {
      if (this.text == '') return this.$message.warning('保存的内容为空')
      if (this.file == null) {
        this.file = { name: 'novel.txt' }
      }
      const element = document.createElement('a')
      element.setAttribute(
        'href',
        'data:text/plain;charset=utf-8,' + encodeURIComponent(this.text)
      )
      element.setAttribute(
        'download',
        timeStampFormatStr(new Date().getTime()) + '——' + this.file.name
      )
      console.log(timeStampFormatStr(new Date().getTime()))
      element.style.display = 'none'
      element.click()
      this.changFlag = ''
    },
    // 编辑小说时触发
    changTextarea(value) {
      value == this.testRes ? (this.changFlag = '') : (this.changFlag = 'new')
    },
    // 检索违规字段
    retrieval() {
      if (this.state == '') return this.$message.warning('请选择或输入关键词')
      if(this.text=='') return this.$message.warning('当前文章内容为空')
      console.info(this.text.indexOf(this.state))
      if (!(this.text.indexOf(this.state) > 0))
        return this.$message.success('该文章没有违规字')
      // let intext =document.getElementById('content').innerText
      this.exhibition = this.text
      this.exhibition = this.exhibition.replace(
        new RegExp(this.state, 'g'),
        `<span style="color:red;">${this.state}</span>`
      )
      console.info(this.exhibition)
      //  console.info(ee)
      this.dialogFormVisible = true
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        )
      }
    },
    loadAll() {
      return keyword()
    },
    handleSelect(item) {
      console.log(item)
    },
    handleIconClick(ev) {
      console.log(ev)
    },
    // 读取文件的 内容到 文本域中
    readT(file) {
      this.file = file
      console.info(file)
      const privateKeyFile = file.raw
      let reader = new FileReader()
      if (typeof FileReader === 'undefined') {
        this.$message({
          type: 'info',
          message: '您的浏览器不支持FileReader接口'
        })
        return
      }
      reader.readAsText(privateKeyFile)
      reader.onload = e => {
        let res = e.target.result
        this.text = res
        this.testRes = res
      }
    },
    // 返回章节添加页面
    goBack() {
      this.$router.push({
        path: '/chapteron'
      })
    }
  },
  // vue生命周期函数 已进入页面请求 违规关键字
  mounted() {
    this.restaurants = this.loadAll()
  },
  // 路由守卫
  beforeRouteLeave(to, from, next) {
    // 这里需要elementui的支持，如果使用其他界面组件自行替换即可
    this.$confirm('正在离开本页面，本页面内所有未保存数据都会丢失', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        // 正常跳转
        next()
      })
      .catch(() => {
        // 如果取消跳转地址栏会变化，这时保持地址栏不变
        window.history.go(1)
      })
  }
}
</script>
<style lang="less" scoped>
.app {
  height: 100%;
}

.tip {
  font-size: 15px;
  color: rgb(175, 173, 173);
  margin-bottom: 10px;
}
.tip::before {
  content: '*';
  font-size: 15px;
  color: rgb(247, 9, 9);
}
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
.inputKeyword {
  margin: 0px 20px 0px 100px;
}
.goBack {
  float: right;
  margin-right: 40px;
}
</style>
